package cn.lingyangwl.framework.log;

import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import cn.lingyangwl.framework.log.common.LogCons;
import cn.lingyangwl.framework.log.utils.MDCTraceUtils;
import cn.lingyangwl.framework.tool.core.CollectionUtils;
import cn.lingyangwl.framework.tool.core.StringUtils;
import org.slf4j.MDC;

import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 打印堆栈信息携带traceId
 * @author shenguangyang
 */
public class CompressedStackTraceConverter extends ThrowableProxyConverter {
    public static Pattern pattern;

    public static void init(LyLogProperties logProperties) {
        if (CollectionUtils.isEmpty(logProperties.getThrowableFilter())) {
            return;
        }
        StringBuilder regexp = new StringBuilder();
        for (String word : logProperties.getThrowableFilter()) {
            regexp.append("(?=.*").append(word).append(")");
        }
        pattern = Pattern.compile(regexp.toString());
    }

    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        String original = super.throwableProxyToString(tp);
        String loginId = StringUtils.defaultString(MDC.get(LogCons.LOGIN_ID), "");
        String traceId = StringUtils.defaultString( MDCTraceUtils.getTraceId(), "");

        String content = StringUtils.isAllEmpty(loginId, traceId) ? "" : loginId + "," + traceId;
        traceId = " [" + content + "]";
        String lineFeed = !original.contains("\r\n") ? "\n" : "\r\n";
        if (Objects.nonNull(pattern)) {
            original = Arrays.stream(original.split(lineFeed)).filter(line -> pattern.matcher(line).find())
                    .collect(Collectors.joining(lineFeed));
        }
        return original.replaceAll(lineFeed, traceId + lineFeed);
    }
}
